package com.example.service;

import java.nio.file.Path;
import java.util.concurrent.CompletableFuture;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.example.infrastructure.FileService;
import com.example.infrastructure.IntentService;
import com.example.infrastructure.TtsService;
import com.example.model.IntentResponseModel;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Sinks;

@Component
public class AudioService {

	private final Sinks.Many<IntentResponseModel> transcriptionSink = Sinks.many().multicast().onBackpressureBuffer();

	@Autowired
	private IntentService intentService;

	@Autowired
	private TtsService ttsService;

	@Autowired
	private FileService fileService;

	public void processAudio(MultipartFile audioFile) {
		CompletableFuture.runAsync(() -> {
			String text = "";
			Path filePath = null;
			try {

				filePath = fileService.saveFile(audioFile);
				text = ttsService.llmResolveText(filePath);
				IntentResponseModel dto = intentService.llmResolveIntent(text);
				transcriptionSink.tryEmitNext(dto);
			} catch (Exception e) {
				transcriptionSink.tryEmitNext(new IntentResponseModel(text, IntentResponseModel.INTENT_UNKNOWN, null));
			} finally {
				fileService.deleteFile(filePath);
			}
		});
	}

	public Flux<IntentResponseModel> getTranscriptionStream() {
		return transcriptionSink.asFlux();
	}
}
